package org.abettor.angleworm.ui;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Properties;

import org.abettor.angleworm.i18n.Translator;
import org.abettor.angleworm.util.Configuration;
import org.abettor.util.Environment;
import org.abettor.util.StringTool;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Combo;

public class LanguageSwitchDialog
{
	private static Translator translator = null;
	private static final int WIDTH = 300;
	private static final int HEIGHT = 220;
	private String language = null;
	private Display display = Display.getDefault();
	private Shell languageShell = null;
	private Label labelPrompt = null;
	private Combo comboLanguage = null;
	private Button buttonSwitch = null;
	private Button buttonComplete = null;

	public void show()
	{
		createLanguageShell();
		languageShell.open();
		while(! languageShell.isDisposed())
		{
			if(! display.readAndDispatch())
			{
				display.sleep();
			}
		}
	}

	public void createLanguageShell()
	{
		try
		{
			translator = Translator.getInstance();
			if(translator == null)
			{
				translator = Translator.initialize("en_US");
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return;
		}

		GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		Monitor monitor = display.getPrimaryMonitor();
        Rectangle rect = monitor.getBounds();
		languageShell = new Shell(SWT.MIN | SWT.CLOSE);
		languageShell.setText(translator.getString("language.dialog.title"));
		languageShell.setSize(new Point(WIDTH, HEIGHT));
		languageShell.setLocation((rect.width - WIDTH) / 2, (rect.height - HEIGHT) / 2);
		languageShell.setImage(new Image(display, Environment.getFilePath("img/logo.png")));
		languageShell.setLayout(gridLayout);

		GridData gridDataPrompt = new GridData();
		gridDataPrompt.horizontalSpan = 2;
		gridDataPrompt.grabExcessHorizontalSpace = true;
		gridDataPrompt.horizontalAlignment = GridData.BEGINNING;
		labelPrompt = new Label(languageShell, SWT.NONE);
		labelPrompt.setText(translator.getString("language.dialog.prompt"));

		createComboLanguage();

		GridData gridDataSwitch = new GridData();
		gridDataSwitch.grabExcessHorizontalSpace = true;
		gridDataSwitch.horizontalAlignment = GridData.END;
		buttonSwitch = new Button(languageShell, SWT.NONE);
		buttonSwitch.setLayoutData(gridDataSwitch);
		buttonSwitch.setText(translator.getString("language.dialog.button.switch"));

		buttonComplete = new Button(languageShell, SWT.NONE);
		buttonComplete.setLayoutData(new GridData());
		buttonComplete.setText(translator.getString("language.dialog.button.proceed"));
		languageShell.pack();

		buttonSwitch.addSelectionListener(new SelectionAdapter()
		{
			@Override
			public void widgetSelected(SelectionEvent e)
			{
				String selected = comboLanguage.getText();
				int idx = selected.indexOf(":");
				language = selected.substring(0, idx);
				languageShell.close();
			}
		});
		buttonComplete.addSelectionListener(new SelectionAdapter()
		{
			@Override
			public void widgetSelected(SelectionEvent e)
			{
				language = null;
				languageShell.close();
			}
		});
	}

	private void createComboLanguage()
	{
		List<String> items = new ArrayList<String>();
		String langPath = Environment.getFilePath("conf/language");
		File langFolder = new File(langPath);
		File[] languages = langFolder.listFiles(new FilenameFilter()
		{
			@Override
			public boolean accept(File dir, String name)
			{
				if(name.endsWith(".properties"))
				{
					return true;
				}

				return false;
			}
		});
		for(File lang : languages)
		{
			String fileName = lang.getName();
			int idx = fileName.indexOf(".");
			fileName = fileName.substring(0, idx);
			InputStream is = null;
			try
			{
				is = new FileInputStream(lang);
				Properties props = new Properties();
				props.load(is);
				items.add(fileName + ": " + props.getProperty("global.language.name"));
			}
			catch (FileNotFoundException e)
			{
				e.printStackTrace();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
			finally
			{
				if(is != null)
				{
					try
					{
						is.close();
					}
					catch (IOException e)
					{
						e.printStackTrace();
					}
				}
			}
		}
		Collections.sort(items, new Comparator<String>()
		{
			@Override
			public int compare(String arg0, String arg1)
			{
				try
				{
					return StringTool.compare(arg0, arg1);
				}
				catch (UnsupportedEncodingException e)
				{
					e.printStackTrace();
				}
				return 0;
			}
		});
		String[] itemArray = new String[items.size()];
		items.toArray(itemArray);

		GridData gridDataCombo = new GridData();
		gridDataCombo.grabExcessHorizontalSpace = true;
		gridDataCombo.horizontalAlignment = GridData.CENTER;
		gridDataCombo.grabExcessVerticalSpace = true;
		gridDataCombo.verticalAlignment = GridData.CENTER;
		gridDataCombo.horizontalSpan = 2;
		comboLanguage = new Combo(languageShell, SWT.NONE | SWT.READ_ONLY);
		comboLanguage.setItems(itemArray);
		comboLanguage.setLayoutData(gridDataCombo);

		String currentLanguage = Configuration.getDefaultLanguage();
		if(currentLanguage == null || currentLanguage.isEmpty())
		{
			currentLanguage = "en_US";
		}
		String langFilePath = Environment.getFilePath("conf/language/" + currentLanguage + ".properties");
		File langFile = new File(langFilePath);
		InputStream is = null;
		try
		{
			is = new FileInputStream(langFile);
			Properties props = new Properties();
			props.load(is);
			comboLanguage.setText(currentLanguage + ": " + props.getProperty("global.language.name"));
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		finally
		{
			if(is != null)
			{
				try
				{
					is.close();
				}
				catch (IOException e)
				{
					e.printStackTrace();
				}
			}
		}
	}

	public String getLanguage()
	{
		return language;
	}
}
